package kr.saeildamil.androidstudty.ch17;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;

public class SaveState extends Activity {
	private MyView vw;
	int x;
	int y; 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(savedInstanceState==null){
			x=50;
		}else{
			x=savedInstanceState.getInt("x");
		}
		SharedPreferences pref=getSharedPreferences("SaveState", MODE_PRIVATE);
		y=pref.getInt("y", 0);
		vw=new MyView(this);
		vw.setFocusable(true);
		vw.setFocusableInTouchMode(true);
		setContentView(vw);
	}
	@Override
	protected void onPause() {
		super.onPause();
		SharedPreferences pref
		=getSharedPreferences("SaveState", MODE_PRIVATE);//sharedpreferences를 사용하면 액티비티가 종료되어도 영구적으로 정보가 저장된다
		SharedPreferences.Editor edit=pref.edit();
		edit.putInt("y", y);
		edit.commit();	//저장
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putInt("x", x);	//x값만 저장
	}

	protected class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);
			Paint p=new Paint();
			p.setColor(Color.GREEN);
			canvas.drawCircle(x, y, 16, p);
		}
		
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			super.onTouchEvent(event);
			if(event.getAction()==MotionEvent.ACTION_DOWN){
				x+=15;
				y+=15;
				invalidate();
				return true;
			}
			return false;
		}
		
	}
}
